#include "studytablemodel.h"

StudyTableModel::StudyTableModel(QObject *parent, QSqlDatabase db) :
    QSqlRelationalTableModel(parent, db)
{
    setTable("study_t");
    setRelation(InstiId_FK, QSqlRelation("institution_t", "insti_id", "name"));
    setRelation(TaskPhy_FK, QSqlRelation("user_t", "user_id", "name"));
    setRelation(StateId_FK, QSqlRelation("status_t", "stat_id", "stat_text"));
    setSort(StudyTime, Qt::DescendingOrder);
}

void StudyTableModel::applyFilter()
{
    QString filter;
    if (fromTime.isValid()) {
        filter += QString("study_time>\'%1\'").arg(fromTime.toString("yyyy-MM-dd hh:mm:ss"));
    }
    if (toTime.isValid()) {
        if (!filter.isEmpty()) filter += " and ";
        filter += QString("study_time<\'%1\'").arg(toTime.toString("yyyy-MM-dd hh:mm:ss"));
    }
    if (!moda.isEmpty()) {
        if (!filter.isEmpty()) filter += " and ";
        filter += QString("modality=\'%1\'").arg(moda);
    }
    if (!patiId.isEmpty()) {
        if (!filter.isEmpty()) filter += " and ";
        filter += QString("pati_id LIKE \'%%1%\'").arg(patiId);
    }
    if (!patiName.isEmpty()) {
        if (!filter.isEmpty()) filter += " and ";
        filter += QString("pati_name LIKE \'%%1%\'").arg(patiName);
    }
    if (!accNum.isEmpty()) {
        if (!filter.isEmpty()) filter += " and ";
        filter += QString("acc_num LIKE \'%%1%\'").arg(accNum);
    }

    setFilter(filter);
}
